
const {getMenuBy} = require('../service/menu.service');

const {
  menuFormateError,
  menuAlreadyExited,
  menuleDoesNotExist,
  menuInsertError,
  menuIdFormateError
} = require('../constant/err.type')

// 验证菜单名是否为空
const menuValidator = async (ctx, next) => {
  const {name} = ctx.request.body

  if(!name) {
    console.error('菜单名为空', ctx.request.body)
    ctx.response.body = menuFormateError
    return
  }
  await next()
}
// 验证id是否为空
const menuIdValidator = async (ctx, next) => {
  const {id} = ctx.request.body

  if(!id) {
    ctx.response.body = menuIdFormateError
    return
  }
  await next()
}

// 验证id是不存在
const menuIdHas = async (ctx, next) => {
  const {id} = ctx.request.body

  try{
    const res = await getMenuBy({id})
    if(!res || res.length === 0) {
      console.error('不存在此菜单id', ctx.request.body)
      ctx.response.body = menuleDoesNotExist
      return
    }
   
  } catch(err) {
    console.log('获取菜单信息错误', err)
    ctx.response.body = menuInsertError
    return
  }
  await next()
}

// 验证该菜单是否存在
const hasMenu = async (ctx, next) => {
  const {name} = ctx.request.body;

  try {
    const res = await getMenuBy({name})
    if(res && res.length > 0) {
      console.error('该菜单已经存在，请勿重复添加！', { name })
      ctx.response.body = menuAlreadyExited
      return
    } 
  } catch(err) {
    console.error('获取菜单信息错误', err)
    ctx.response.body = menuInsertError
  }
  await next()
}



module.exports = {hasMenu, menuValidator, menuIdValidator, menuIdHas}